using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;

using Pampa.Grid.Core;
using Pampa.Grid.Exceptions;

namespace Pampa.Grid.Data
{
    public abstract class GridDataReader
    {
        public abstract void Open(Configuration configuration, int pageSize, int pageNumber);
        public abstract bool Read();
        public abstract object GetValue(string fieldName);
        public abstract void Close();

        public abstract int GetCount(Configuration configuration);

        public abstract void LoadXml(XmlNode node);
        public abstract void ToXml(ref XmlNode root);

        public static GridDataReader LoadFromXml(XmlNode rootNode)
        {
            XmlNamespaceManager nsManager = new XmlNamespaceManager(rootNode.OwnerDocument.NameTable);
            nsManager.AddNamespace("pampa", rootNode.NamespaceURI);

            XmlNode nodeDataReader = rootNode.SelectSingleNode("pampa:DataReader", nsManager);

            if (nodeDataReader == null)
                throw (new GridConfigurationException("Node 'DataReader' was not found."));

            if (nodeDataReader.Attributes["Type"] == null)
                throw (new GridConfigurationException("Attribute 'Type' can not be found in node 'DataReader'."));

            string DataReaderClassName = nodeDataReader.Attributes["Type"].Value.ToString();
            Type type = Type.GetType(DataReaderClassName);
            
            if (type == null)
                throw (new GridConfigurationException("DataReader class name '" + DataReaderClassName + "' is not valid."));

            GridDataReader DataReader = (GridDataReader)Activator.CreateInstance(type);
            DataReader.LoadXml(nodeDataReader);

            return DataReader;
        }
    }
}
